package unilearn.da;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.commons.fileupload.util.Streams;

import unilearn.domain.DataFile;

public class DAFile extends DABase
{
	public DAFile()
	{
	}

	public static long insertFile(DataFile file) throws SQLException, IOException
	{
		long newId = 0;
		PreparedStatement ps = null;

		try
		{
			Connection conn = getConn();

			ps = conn.prepareStatement(
					"insert into data_file(file_name,file_type,file_size,file_data) values(?,?,?,?)",
					Statement.RETURN_GENERATED_KEYS);

			ps.setString(1, file.getFileName());
			ps.setString(2, file.getFileType());
			ps.setLong(3, file.getFileSize());

			FileInputStream fileInStream = new FileInputStream(file.getFile());
			ps.setBinaryStream(4, fileInStream, (int) file.getFileSize());
			ps.execute();

			ResultSet results = ps.getGeneratedKeys();
			if (results.next())
			{
				newId = results.getLong(1);
			}

		}
		finally
		{
			ps.close();
		}

		return newId;
	}

	public static DataFile getByFileID(long fileID) throws SQLException, IOException
	{
		DataFile file = null;
		PreparedStatement ps = null;

		try
		{
			Connection conn = getConn();

			ps = conn.prepareStatement("select * from data_file where file_id = ?");
			ps.setLong(1, fileID);
			ResultSet rs = ps.executeQuery();

			if (rs.next())
			{
				file = new DataFile(rs.getLong("file_id"));
				file.setFileName(rs.getString("file_name"));
				file.setFileSize(rs.getLong("file_size"));
				file.setFileType(rs.getString("file_type"));

				Blob fileBlob = rs.getBlob("file_data");
				InputStream inStream = fileBlob.getBinaryStream();
				File tempFile = File.createTempFile("download", ".tmp");
				FileOutputStream outStream = new FileOutputStream(tempFile);
				Streams.copy(inStream, outStream, true);
				file.setFile(tempFile);
			}
		}
		finally
		{
			ps.close();
		}

		return file;
	}
}
